import { DownOutlined, PlusOutlined,CheckOutlined,MinusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button,  Dropdown, Menu, Radio, message,Popconfirm,Switch,Row,Col,Divider,Input,Table,Icon} from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import DataForm from './components/DataForm';
import HelpForm from './components/HelpForm';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule,updateItemRule,setDefaultRule,setMulLangRule,updateRankRule } from './service';
import styles from './style.less';
import router from 'umi/router';

import * as RequestHelper from '@/helpers/RequestHelper';
import PreviewForm from '@/components/PreviewForm';
import * as TsxHelper from '@/helpers/TsxHelper';
import { EditableFormRow, EditableCell } from './components/BDEditable';
interface TableListProps extends FormComponentProps {}


const TableList: React.FC<TableListProps> = () => {
    // 初始化变量区
    // 维护API状态数据
    const [apiState, setApiState] = useState<any>({common:{}});
    const [common, setCommon] = useState<any>({});
    // 是否更新 关键变量
    const [isUpdate, setIsUpdate] = useState<boolean>(false);
    // 表单可见 关键变量
    const [dataModalVisible, handleDataModalVisible] = useState<boolean>(false);
    const [helpModalVisible, handleHelpModalVisible] = useState<boolean>(false);
    // 图片预览
    const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
    const [previewImg, setPreviewImg] = useState('');
    // 表单数据
    const [dataFormValues, setDataFormValues] = useState({});
    // 选中的记录
    const [rowKeys, setRowKeys] = useState<string[]|number[]>([]);

    //列表数据
    const [dataList,setDataList] = useState<any>([]);

    //多语言列表数据
    const [langList, setLangList] = useState<any>([]);

    const actionRef = useRef<ActionType>();

    useEffect(()=>{
        getTableData();
    },[])

    // 列定义
    const columns = [
        {
            title: formatMessage({ id: 'ranknum' }),
            dataIndex: 'rankNum',
            width:200,
            editable: true,
            // render: (value:any,record) => (
            //     <Input  defaultValue={value} onPressEnter={async (e) => {
            //         let s = await handleUpdateItem({ key: record.key, rankNum: e.target.value });
            //         s && actionRef.current?.reload();
            //     }}/>
            // )
        },
        {
            title: formatMessage({ id: 'default-language' }),
            dataIndex: 'langTag',
            render:(value:any,record:any) =>(
              <Radio.Group onChange={(e)=>{setDefaultLang(e.target.value)}} defaultValue={common.default_language} value={common.default_language}>
                <Radio  value={record.langTag}>默认</Radio>
              </Radio.Group>
            )
        },
        {
            title: formatMessage({ id: 'lang_code' }),
            dataIndex: 'langCode',
        },
        {
            title: formatMessage({ id: 'area_code' }),
            dataIndex: 'areaCode',
        },
        {
            title: formatMessage({ id: 'language-name' }),
            dataIndex: 'langName',
        },
        {
            title: formatMessage({ id: 'area-name' }),
            dataIndex: 'areaName',
        },
        {
            title: formatMessage({ id: 'length-unit' }),
            dataIndex:'lengthUnits',
        },
        {
            title: formatMessage({ id: 'presentation-direction' }),
            dataIndex: 'writingDirection',
        },
        {
            title: formatMessage({ id: 'start-status' }),
            dataIndex: 'isEnable',
            render: (value:any,record:any) => (value ? <CheckOutlined style={{ fontSize: '20px',color:'#198754', }}/> : <MinusOutlined style={{ fontSize: '20px' }}/>),
        },
        // {
        //     title: formatMessage({id: 'Language-pack-management'}),
        //     dataIndex: 'langpack',
        //     render: (_,record:any) => (
        //         <Button type="default" onClick={()=>{router.push(`/system/lang-package-setting?key=${record.key}&langtag=${record.langTag}`)}}>配置</Button>
        //     )
        // },
        {
            title: formatMessage({ id: 'app.base.option' }),
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record:any) => (
                <>
                <a
                    onClick={() => {
                        handleDataModalVisible(true);
                        setDataFormValues(record);
                        console.log(record);
                        setIsUpdate(true);
                    }}
                >
                    编辑
                </a>
                <Divider type="vertical"/>
                <Button type="default" onClick={()=>{router.push(`/system/lang-package-setting?langtag=${record.langTag}`)}}>配置语言包</Button>
                <Divider type="vertical"/>
                <Popconfirm
                  title="确认删除吗？"
                  onConfirm={()=>{deleteData(record.langTag)}}
                  okText="确认"
                  cancelText="取消"
                >
                  <a>删除</a>
                </Popconfirm>
                </>
            ),
        },
    ];

    // 请求接口数据, 设置组件状态
    const getTableData = () => {
        //请求当前一组配置参数，tag=languages
        queryRule({tag:'languages'}).then((res:any) => {
            if(res.code == 0){
                setCommon(res.data.common)
                if(res.data.list && res.data.list.length>0){
                    setLangList(res.data.list[0]?.item_value_decode);
                    console.log(res.data.list[0]?.item_value_decode);
                    const listData = {
                      data: res.data.list[0]?.item_value_decode
                    }
                    return listData
                }else{
                    return []
                }
            }else{
                message.error(res.message);
            }
            
            
        })
    }

    //删除接口
    const deleteData = (id:any) => {
        var params = {
            ids: id,
        }
        removeRule(params).then(res=>{
            if(res.code == 0){
                message.success('删除成功！')
                
            }else{
                message.error(res.message)
            }
            getTableData();
        })
    }

    //设置默认
    const setDefaultLang = (defaultkey: any) => {
      console.log(defaultkey);
      setDefaultRule({langTag: defaultkey}).then(res=>{
        if(res.code == 0){
            message.success('设置成功')
            getTableData();
        }else{
            message.error(res.message);
        }
      })
    }

    //是否开启多语言
    const isOpenMulLang = (status: any) => {
      console.log(status);
      setMulLangRule({language_status: status}).then(res=>{
        if(res.code == 0){
          message.success('设置成功')
          getTableData();
        }else{
            message.error(res.message);
        }
      })
    }

    // 表单提交
    const handleSubmitDataForm = (value:any) => {
        console.log(value)

        return new Promise((resolve, reject) => {
            let s =  isUpdate ? handleUpdate(value)  : handleAdd(value);
            resolve(s);
        }).then( status => {
            console.log("handleSubmitDataForm status is ", status)
            if(status){
                handleDataModalVisible(false)
                setIsUpdate(false)
                setDataFormValues({})
                getTableData();
            }
            // 返回执行结果:boolean, 子组件接收此值来重置数据
            return status;
        })
    }

    const handleSave = (row:any) => {
        const newData = [...langList];
        const index = newData.findIndex(item => row.langTag === item.langTag);
        const item = newData[index];
        newData.splice(index, 1, {
          ...item,
          ...row,
        });
        // this.setState({ dataSource: newData });
        setLangList(newData);
    };

    const newcolumns = columns.map(col => {
        if (!col.editable) {
          return col;
        }
        return {
          ...col,
          onCell: (record:any) => ({
            record,
            editable: col.editable,
            dataIndex: col.dataIndex,
            title: col.title,
            handleSave: (row: any) => handleSave(row),
          }),
        };
      });


    const updateRankNum = () => {
        let arr:any = [];
        if(langList.length>0){
            langList.map((item:any,index:any)=>{
                arr[index]={
                    langTag: item.langTag,
                    rank_num: item.rankNum,
                }
            })
        }
        
        let more_json = JSON.stringify(arr);
        console.log(more_json);
        updateRankRule({more_json: more_json}).then(res=>{
            if(res.code == 0){
                message.success('更新成功！')
                getTableData();
            }else{
                message.error(res.message)
            }        
        })
    }

    const content = (
        <div className={styles.pageHeaderContent}>
            <p>
                多语言需要先在这里配置语言选项，然后才能在对应配置项时录入多语言内容。
            </p>
            {/* <div className={styles.contentLink}>
                <Switch checked={common?.language_status == '1' ? true : false} onChange={(e)=>{isOpenMulLang(e)}}/>
                <span style={{marginLeft:10}}>是否开启多语言</span>
            </div> */}
        </div>
      );


    return (
        <PageHeaderWrapper
            content={content}
        >
            <Row style={{backgroundColor: "#fff",padding:"15px 25px",marginBottom:10,}}>
                <Col style={{display: "flex",justifyContent:"space-between",alignItems:"center"}}>
                    <div className={styles.contentLink}>
                        <Switch checked={common?.language_status == true ? true : false} onChange={(e)=>{isOpenMulLang(e)}}/>
                        <span style={{marginLeft:10}}>是否开启多语言</span>
                        <Button type="primary" style={{marginLeft:10}} onClick={()=>{updateRankNum()}}>更新排序</Button>
                    </div>
                    <div>
                        <Button type="primary" style={{marginRight: 10}} onClick={()=>{setIsUpdate(false); handleDataModalVisible(true);}}>新建</Button> 
                        {/* @ts-ignore */}
                        <Button type="default" icon="exclamation-circle" onClick={()=>{handleHelpModalVisible(true)}}>{formatMessage({id: 'helptext'})}</Button>   
                    </div> 
                    
                </Col>    
            </Row>
          {/* <ProTable<TableListItem>
            headerTitle=""
            actionRef={actionRef}
            rowKey="key"
            search={false}
            pagination={false}
            toolBarRender={(action, { selectedRows }) => [
              // @ts-ignore
              <Button icon={<PlusOutlined />} type="primary" onClick={() => { setIsUpdate(false); handleDataModalVisible(true);console.log(common)}}>
                {formatMessage({ id: 'app.base.create' })}
              </Button>,
          ]}
            request={params => getTableData(params)}
            columns={columns}
            /> */}
            {/* <Row style={{backgroundColor: "#fff",padding:"15px 25px",marginBottom:10,}}>
                <Col style={{display: "flex",justifyContent:"space-between",alignItems:"center"}}>
                    <Button type="primary" onClick={()=>{updateRankNum();}}>更新</Button>
                    <Button type="primary" onClick={()=>{setIsUpdate(false); handleDataModalVisible(true);}}>新建</Button>
                </Col>    
            </Row> */}
            <Table 
                style={{backgroundColor: "#fff"}}
                components={{
                    body: {
                      row: EditableFormRow,
                      cell: EditableCell,
                    },
                }}
                rowClassName={() => 'editable-row'}
                columns={newcolumns}
                dataSource={langList}
                pagination={false}
            />
            <DataForm
                dataModalVisible={dataModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={common || {}}
                dataList={dataList}
                onSubmit={ async formValue => handleSubmitDataForm(formValue) }
                onCancel={() => handleDataModalVisible(false)}
            />
            <HelpForm
                dataModalVisible={helpModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={common || {}}
                dataList={dataList}
                onSubmit={ () => handleHelpModalVisible(false) }
                onCancel={() => handleHelpModalVisible(false)}
            />
              {
                  previewModelVisible && (
                      <PreviewForm
                          previewModelVisible={previewModelVisible}
                          onVisibleModel={handlePreviewModalVisible}
                          previewImg={previewImg}
                      />
                  )
              }
        </PageHeaderWrapper>
    );
};

/**
* 添加节点
* @param fields
*/
const handleAdd = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: addRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.store-success' }),
        failMsg: formatMessage({ id: 'app.base.api-exception' }),
    });
};

/**
* 更新节点
* @param fields
*/
const handleUpdate = async (fields: any) => {
    return RequestHelper.bdExec({
        fn: updateItemRule,
        args: fields,
        successMsg: formatMessage({ id: 'app.base.update-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
    });
};
const handleUpdateItem = async (fields: any) => {
    return RequestHelper.bdExec({ fn: updateItemRule, args: fields, successMsg: '更新成功', failMsg: '更新失败请重试！' });
};

// @ts-ignore
/**
 *  删除节点
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
    if (!selectedRows) return true;
    const ids:any = selectedRows.map(row => row.key).toString();
    return RequestHelper.bdExec({
        fn: removeRule,
        args: {ids},
        successMsg: formatMessage({ id: 'app.base.destroy-success' }),
        failMsg:  formatMessage({ id: 'app.base.api-exception' }),
        hasLoading: false
    });
};


export default Form.create<TableListProps>()(TableList);
